#include "stdafx.h"
#include "ChatServer.h"
#include "ChatFakeNet.h"

const int SleepMSOnce = 1000;

const int MaxFriendCount = 10;
const int MaxMsgCount = 50;

const int MaxFriendNameLength = 5;
const int MaxMsgLength = 30;
const int MinMsgLength = 10;

CRITICAL_SECTION g_CriticalSection;

StringList g_Accounts;

DWORD WINAPI TestSendMsgThread(LPVOID param)
{
	::InitializeCriticalSection(&g_CriticalSection);

	ChatServer* pModel = (ChatServer*)param;
	if (!pModel)
	{
		return 0;
	}

	std::TString msgPool[MaxMsgCount];
	for (int i = 0; i < MaxMsgCount; i++)
	{
		msgPool[i] = std::TString(rand() % (MaxMsgLength - MinMsgLength) + MinMsgLength, rand() % 94 + 33);
	}

	while (true)
	{
		std::TString friendAccount = g_Accounts[rand() % (MaxFriendCount / 2)];
		std::TString randMsg = msgPool[rand() % MaxMsgCount];

		::EnterCriticalSection(&g_CriticalSection);

		pModel->__TestSendMsgToRandAccount(friendAccount, randMsg);

		::LeaveCriticalSection(&g_CriticalSection);

		Sleep(SleepMSOnce);
	}

	::DeleteCriticalSection(&g_CriticalSection);
	return 0;
}


ChatServer::ChatServer()
{
}

ChatServer::~ChatServer()
{
}

void ChatServer::Init()
{
	FakeNetModule::Instance().serverRecvMessage.connect(this, &ChatServer::OnRecvMessage);

	m_ConnectAccounts.push_back(_T("MySelf"));

	for (int i = 0; i < MaxFriendCount; i++)
	{
		g_Accounts.push_back(std::TString(MaxFriendNameLength, rand() % 26 + 65));
	}

	CreateThread(NULL, 0, &TestSendMsgThread, (LPVOID)this, 0, NULL);

}

void ChatServer::Run()
{
	Init();
}

void ChatServer::OnRecvMessage(int msgId, const StringList& msg)
{
	if (msgId==C_S_CHAT_MESSAGE)
	{
		OnRecvChatMessage(msgId, msg);
	}
	else if (msgId == C_S_GET_FRIENDLIST)
	{
		OnRecvGetFriendListMessage(msgId, msg);
	}
	else if (msgId == C_S_SET_FRIEND_INFO)
	{
		// ...
	}
}

void ChatServer::OnRecvGetFriendListMessage(int msgId, const StringList& msg)
{
	FakeNetModule::Instance().SendMessage(S_C_GET_FRIENDLIST, g_Accounts);
}

void ChatServer::OnRecvChatMessage(int msgId, const StringList& msg)
{
	if (msg.size()!=3)
	{
		return;
	}

	m_ConnectAccounts.push_back(msg[0]);

	FakeNetModule::Instance().SendMessage(S_C_CHAT_MESSAGE, msg);
}


void ChatServer::__TestSendMsgToRandAccount(const std::TString& sender, const std::TString& msg)
{
	if (m_ConnectAccounts.size()==0)
	{
		return;
	}

	int index = rand() % m_ConnectAccounts.size();
	const std::TString& recver = m_ConnectAccounts[index];

	StringList msgList;
	msgList.push_back(sender);
	msgList.push_back(recver);
	msgList.push_back(msg);

	FakeNetModule::Instance().SendMessage(S_C_CHAT_MESSAGE, msgList);
}